package com.suncnpap.reader.controller;

import com.suncnpap.reader.model.Reader;
import com.suncnpap.reader.model.ReaderType;
import com.suncnpap.reader.model.ReaderVo;
import com.suncnpap.reader.service.ReaderService;
import com.suncnpap.reader.service.ReaderTypeService;
import com.suncnpap.statistics.annotation.LogType;
import com.suncnpap.statistics.annotation.SysLog;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.suncnpap.system.model.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.app.util.common.HandlerResult;
import com.app.util.common.ObjUtil;
import com.app.util.common.ResponseUtil;
import com.app.util.common.UuidUtil;
import com.app.util.database.mybatis.Page;
import com.app.util.database.mybatis.QueryType;
import com.suncnpap.base.common.ParamModel;
import com.suncnpap.base.controller.BaseController;
import com.suncnpap.datamanage.common.ExportExcelUtils;
import com.suncnpap.journal.model.BorrowJournal;
import com.suncnpap.journal.service.BorrowJournalService;
import com.suncnpap.library.model.BorrowBook;
import com.suncnpap.library.model.Library;
import com.suncnpap.library.service.BorrowBookService;

/** 
 * 说明：读者Controller
 */
@Controller
@RequestMapping(value="/reader/reader")
public class ReaderController extends BaseController {
	
	//private static final Logger log = Logger.getLogger(ReaderController.class);
	
	@Autowired
	ReaderService readerService;
	
	/**
	 * 列表页面数据处理，包括查询
	 * @param
	 * @param response
	 */
	@RequestMapping(value="/list")
	public void list(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		
		if (result.getCode()==0) {

			Page page = this.setPage();
			
			String keyName = this.getParameter("keyName", "");
			String keywords = this.getParameter("keywords", "");
			if(!keyName.equals("")){
				if(keyName.equals("strReaderType")){
					page.addQueryAnd("strReaderType", QueryType.markLIKE, keywords);
				}else if(keyName.equals("strName")){
					page.addQueryAnd("strName", QueryType.markLIKE, keywords);
				}else if(keyName.equals("strCardNumber")){
					page.addQueryAnd("strCardNumber", QueryType.markLIKE, keywords);
				}
			}
			
			String strUnitId = this.getParameter("strUnitId", "");
			if(!strUnitId.equals("")){
				page.addQueryAnd("strUnitId", strUnitId);
			}
			
			String strReaderType = this.getParameter("strReaderType", "");
			if(!strReaderType.equals("")){
				page.addQueryAnd("strReaderType", strReaderType);
			}
			
			String strName = this.getParameter("strName", "");
			if(!strName.equals("")){
				page.addQueryAnd("strName", strName);
			}
			
			String strCardNumber = this.getParameter("strCardNumber", "");
			if(!strCardNumber.equals("")){
				page.addQueryAnd("strCardNumber", strCardNumber);
			}
			
			String strState = this.getParameter("strState", "");
			if(!strState.equals("")){
				if(strState.equals("stop")){
					page.addQueryAnd("intIsStopBy", 1);
				}else if(strState.equals("loss")){
					page.addQueryAnd("intIsReportLoss", 1);
				}else if(strState.equals("stopAndLoss")){
					page.addQueryOr("intIsReportLoss", 1);
					page.addQueryOr("intIsStopBy", 1);
				}
			}
			
			String dtStartRecordDate = this.getParameter("dtStartRecordDate", "");
			if(!dtStartRecordDate.equals("")){
				page.addQueryAnd("dtCreatDate", QueryType.markGTEQ, dtStartRecordDate);
			}
			
			String dtEndRecordDate = this.getParameter("dtEndRecordDate", "");
			if(!dtEndRecordDate.equals("")){
				page.addQueryAnd("dtCreatDate", QueryType.markLTEQ, dtEndRecordDate);
			}
			
			String strStartCardNumber = this.getParameter("strStartCardNumber", "");
			if(!strStartCardNumber.equals("")){
				page.addQueryAnd("strCardNumber", QueryType.markLTEQ, strStartCardNumber);
			}
			
			String strEndCardNumber = this.getParameter("strEndCardNumber", "");
			if(!strEndCardNumber.equals("")){
				page.addQueryAnd("strCardNumber", QueryType.markGTEQ, strEndCardNumber);
			}
			
			page = readerService.list(page);
			
			String isExp = this.getParameter("isExp", "");
			if(isExp.equals("1")){
				List<Reader> libraryList = page.getDataList();
				String header = "序号,卡号,姓名,工号,部门,类型,是否停借,是否挂失,登记日期";
				
				String tableStr = "xh,strCardNumber,strName,strStudentNumber,strUnitName,strReaderType,intIsStopBy,intIsReportLoss,dtCreatDate";
				
				ExportExcelUtils util = new ExportExcelUtils();
				String path = "upload/exp/";
				String fileName = UuidUtil.get32UUID()+".xls";
				util.exportExcel("读者档案", ObjUtil.strToList(header), ObjUtil.strToList(tableStr),libraryList, path, fileName);
				
				result.put("path", path);
				result.put("fileName", fileName);
			}else{
				result = this.returnPage(result, page);
			}
		}
		
		ResponseUtil.writeJson(result, response);

	}
	
	/**
	 * 添加处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	@SysLog(type=LogType.HANDLECARD)
	public void add(@RequestBody Reader obj,HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strSchoolId = String.valueOf(result.get("strSchoolId"));
				
				Reader reader = readerService.findByCardNumber(obj.getStrCardNumber(), strSchoolId);
				if(reader==null){
					super.init(obj);
					obj.setIntIsReportLoss(0);
					obj.setIntIsStopBy(0);
					obj.setIntIntegral(0);
					obj.init();
					readerService.add(obj);
				}else{
					result.setCode(1);
					result.setMessage("该卡号已存在");
				}
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public void update(@RequestBody Reader obj,HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				readerService.update(obj);
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}

	@RequestMapping(value="/getInfo/{card}/{schoolId}",method=RequestMethod.GET)
	public void getInfo(@PathVariable String card,@PathVariable String schoolId,HttpServletResponse response,HttpServletRequest request) throws Exception{
		HandlerResult result = this.checkToken(request);
		Reader reader=null;
		if(result.getCode()==0){
	      reader=readerService.info(card,schoolId);
		}
		result.put("reader",reader);
		ResponseUtil.writeJson(result, response);
	}

	/**
	 * 忘记密码
	 * @param
	 * @param
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/forgetpassword/{strSchoolId}/{userId}/{strPd}",method=RequestMethod.GET)
	public void forgetpassword(@PathVariable String strSchoolId,@PathVariable String userId,
							   @PathVariable String strPd, HttpServletResponse response)
								throws Exception{
		HandlerResult result = new HandlerResult();
		if(result.getCode()==0){
            Reader reader = readerService.findByCardNumber(userId, strSchoolId);
            if(reader==null){
            	result.setMessage("用户不存在");
            	result.setCode(1);
				ResponseUtil.writeJson(result, response);
            	return;
			}
			String strEmailaddr = reader.getStrEmailaddr();
            System.out.println(strEmailaddr);
			String enPassword = Reader.getMd5Password(strPd, reader.getStrSalt());
			Integer forget=readerService.password(strSchoolId,userId,enPassword);
			if(forget>0){
				result.put("forget","重置成功");
			}
		}
		ResponseUtil.writeJson(result, response);
	}

	
	/**
	 * 删除处理
	 * @param
	 * @return
	 */
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public void delete(@RequestBody ParamModel paramModel,HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strId = paramModel.getStrId();
				if(strId != null && !strId.equals("")){
					readerService.deleteMore(strId.split(","));
				}
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	
	@RequestMapping(value="/view")
	public void view(@RequestBody ParamModel paramModel,HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strId = paramModel.getStrId();
				Reader obj = readerService.findById(strId);
				result.put("obj", obj);
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 挂失处理
	 * @param
	 * @return
	 */
	@RequestMapping(value="/setLoss",method=RequestMethod.POST)
	public void setLoss(@RequestBody Reader reader,HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				readerService.setLossById(reader.getStrId(),reader.getIntIsReportLoss(), result.get("strSchoolId").toString());
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 停借处理
	 * @param
	 * @return
	 */
	@RequestMapping(value="/setStopBy",method=RequestMethod.POST)
	public void setStopBy(@RequestBody Reader reader,HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				readerService.setStopById(reader.getStrId(),reader.getIntIsStopBy(), result.get("strSchoolId").toString());
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
}
